package main

import (
	"encoding/json"
	"fmt"
	_ "github.com/jinzhu/gorm/dialects/mysql"
	"database/sql"
)

var (
	db *sql.DB
)


type WebsiteLink struct {
	ID int `json:"id"`
	Name string `json:"name" gorm:"type:varchar(32)"`
	Slink string `json:"slink" gorm:"type:varchar(100)"`
	CategoryId int `json:"category_id" gorm:"type:int(11);default:1"`

}

type WebsiteCategory struct {
	ID int `json:"id"`
	Name string `json:"name" gorm:"type:varchar(32)"`
}

func initDB() (err error)  {
	dsn := "root:root@(127.0.0.1)/site?charset=utf8mb4&parseTime=True&loc=Local"
	db, err = sql.Open("mysql", dsn)
	if err != nil {
		panic(err)
	}
	err = db.Ping()
	if err != nil {
		return err
	}
	return
}


func main(){
	err := initDB()
	if err != nil {
		fmt.Println(err)
	}


	sqlStr := "select website_link.name, website_link.slink, website_category.name from website_link,website_category where website_link.category_id = website_category.id  ORDER BY website_category.`name`;"
	s, err := db.Query(sqlStr)
	if err != nil {
		fmt.Print(err)
		return
	}
	defer  s.Close()
	dst := make(map[string]interface{}, 10)
	for s.Next() {
		var (
			website_link WebsiteLink
			website_category WebsiteCategory

		)
		err := s.Scan(&website_link.Name, &website_link.Slink, &website_category.Name)
		if err != nil {
			fmt.Println(err)
			return
		}
		fmt.Printf("link_name: %s link_slink: %s category_nme: %s\n",website_link.Name, website_link.Slink, website_category.Name)


		dst["name"] = website_category.Name
		a := []string{}
		b, _ := json.Marshal(map[string]string{
			"name": website_link.Name,
			"link": website_link.Slink,})

		dst["slink"] = append(a, string(b))
		dst["link"] = map[string]string {
			"name": website_link.Name,
			"link": website_link.Slink,
		}

	}
	ret, err := json.Marshal(dst)
	if err != nil {
		fmt.Println(err)
		return
	}
	fmt.Println(string(ret))
}